package com.rzico.sbl.ui.report.depot

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDepotEditBinding
import com.rzico.sbl.model.DepotGoods
import com.rzico.sbl.model.DepotInput
import com.rzico.sbl.model.DepotStation
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject

class ReportDepotEditActivity : BaseActivity(R.layout.activity_report_depot_edit) {

    private val mBinding by lazy { ActivityReportDepotEditBinding.bind(getRootView()) }

    private val mBarrelList = ArrayList<DepotGoods>()
    private val mOutList = ArrayList<Int>()
    private val mRottenList = ArrayList<DepotGoods>()

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun initData() {
        initTitle(title = "空桶入库")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding
            .depotInput
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(
                    SpaceTBDecoration(
                        top = 6f,
                        hasHeader = false,
                        hasFooter = false
                    )
                )

                mAdapter = SlimAdapter.creator()
                    .register<DepotInput>(R.layout.item_report_depot_input) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_depot_title, bean.name)

                            with<EditText>(R.id.item_depot_count) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.quantity = s.toString()

                                        totalReal()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    override fun initListener() {
        mBinding.apply {
            depotSure.oneClick {
                if (mList.any { (it as DepotInput).quantity.isEmpty() }) {
                    showToast("请输入实际入库数量")
                    return@oneClick
                }

                // 品牌空桶
                val barrelItems = mList
                    .filter {
                        it as DepotInput
                        it.status == "barrel"
                    }

                // 外品牌空桶
                val outData = mList
                    .lastOrNull {
                        it as DepotInput
                        it.status == "change"
                    } as DepotInput?

                getViewModel()
                    .request(
                        requestUrl = ReportUrl.getBaseUrl().depotInCfm,
                        params = arrayOf(
                            "id" to intent.getExtra("groupId"),
                            "percent" to (outData?.quantity ?: ""),
                            "body" to Gson().toJson(barrelItems)
                        ),
                        onSuccess = {
                            showToast("入库提交成功！")

                            // 刷新司机入库列表
                            LiveEventBus
                                .get("deliverModify")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    /**
     * 入库详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .request(
                requestUrl = ReportUrl.getBaseUrl().depotInDet,
                requestMethod = HttpMethod.GET,
                params = arrayOf("id" to intent.getExtra("groupId")),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mBinding.apply {
                        depotDriver.text = obj.optNotNull("name")

                        mBarrelList.clear()
                        mOutList.clear()
                        mRottenList.clear()

                        // 出库商品
                        val objGoods = obj.optJSONArray("productList") ?: JSONArray()

                        // 入库品牌空桶
                        val objBarrel = obj.optJSONArray("barrelList") ?: JSONArray()
                        mBarrelList.addItems(
                            JsonUtil
                                .toList(
                                    objBarrel.toString(),
                                    DepotGoods::class.java
                                )
                        )

                        // 入库外品牌空桶
                        val objOut = obj.optJSONObject("percent") ?: JSONObject()
                        mOutList.addItems(
                            listOf(
                                objOut.optNotNull("percent1").intValue,
                                objOut.optNotNull("percent2").intValue,
                                objOut.optNotNull("percent3").intValue,
                                objOut.optNotNull("percent4").intValue
                            )
                        )

                        // 入库烂桶
                        val objRotten = obj.optJSONArray("swapList") ?: JSONArray()
                        mRottenList.addItems(
                            JsonUtil
                                .toList(
                                    objRotten.toString(),
                                    DepotGoods::class.java
                                )
                        )

                        // 订单编号
                        val objSn = obj.optJSONArray("snList") ?: JSONArray()

                        setGoodsData(objGoods.toString())
                        setBarrelData()
                        setOutData()
                        setRottenData()
                        setOrderData(objSn.toString())
                        totalCount()

                        // 输入数据
                        setInputData()
                    }
                }
            )
    }

    /**
     * 出库商品
     */
    private fun setGoodsData(jsonGoods: String) {
        mBinding.apply {
            depotGoods.removeAllViews()

            JsonUtil
                .toList<DepotGoods>(
                    jsonGoods,
                    DepotGoods::class.java
                )
                .forEach {
                    depotGoods.addView(
                        inflate<View>(R.layout.content_report_depot_hint).apply {
                            find<TextView>(R.id.conent_title).text = it.name
                            find<TextView>(R.id.conent_num).text = it.quantity
                        }
                    )
                }
        }
    }

    /**
     * 入库品牌空桶
     */
    private fun setBarrelData() {
        mBinding.apply {
            depotContent.removeAllViews()

            mBarrelList.forEach {
                depotContent.addView(
                    inflate<View>(R.layout.content_report_depot_hint).apply {
                        find<TextView>(R.id.conent_title).text = it.name
                        find<TextView>(R.id.conent_num).text = it.quantity
                    }
                )
            }
        }
    }

    /**
     * 入库外品牌空桶
     */
    private fun setOutData() {
        mBinding.apply {
            depotOther.removeAllViews()

            mOutList
                .also { if (it.sum() > 0) depotOtherHint.visible() }
                .forEachIndexed { index, item ->
                    if (item > 0) {
                        depotOther.addView(
                            inflate<View>(R.layout.content_report_depot_hint).apply {
                                find<TextView>(R.id.conent_title)
                                    .text = when (index) {
                                    0 -> "外品牌1:1"
                                    1 -> "外品牌2:1"
                                    2 -> "外品牌3:1"
                                    3 -> "外品牌补差价"
                                    else -> ""
                                }
                                find<TextView>(R.id.conent_num).text = item.toString()
                            }
                        )
                    }
                }
        }
    }

    /**
     * 入库烂桶
     */
    private fun setRottenData() {
        mBinding.apply {
            depotRotten.removeAllViews()

            mRottenList
                .also { if (it.isNotEmpty()) depotRottenHint.visible() }
                .forEach {
                    depotRotten.addView(
                        inflate<View>(R.layout.content_report_depot_hint).apply {
                            find<TextView>(R.id.conent_title).text = "${it.name}(${it.barrelName})"
                            find<TextView>(R.id.conent_num).text = it.quantity
                        }
                    )
                }
        }
    }

    /**
     * 订单编号
     */
    private fun setOrderData(jsonSn: String) {
        mBinding.apply {
            depotSn.removeAllViews()

            JsonUtil
                .toList<DepotStation>(
                    jsonSn,
                    DepotStation::class.java
                )
                .forEach { itme ->
                    depotSn.addView(
                        inflate<View>(R.layout.content_report_depot_station).apply {
                            find<TextView>(R.id.conent_title).apply {
                                text = "${itme.sn}(${itme.name})"

                                oneClick {
                                    goToOrderDetail("orderSn" to itme.sn)
                                }
                            }
                        }
                    )
                }
        }
    }

    /**
     * 输入数据
     */
    private fun setInputData() {
        mBinding.depotReal.text = "0"
        mList.clear()

        lifecycleScope.launch {
            mBarrelList.forEach {
                mList.add(
                    DepotInput(
                        id = it.barrel,
                        name = it.name,
                        status = "barrel"
                    )
                )
            }

            if (mOutList.sum() > 0)
                mList.add(
                    DepotInput(
                        name = "外品牌空桶",
                        status = "change"
                    )
                )

            mAdapter.setDataList(mList)
        }
    }

    /**
     * 合计空桶数量
     */
    private fun totalCount() {
        lifecycleScope.launch(Dispatchers.IO) {
            var totalCount = 0

            totalCount += mBarrelList.sumOf { it.quantity.intValue }
            totalCount += mOutList.sum()

            withContext(Dispatchers.Main) {
                mBinding.depotTotal.text = "$totalCount"
            }
        }
    }

    /**
     * 实际入库空桶数量
     */
    private fun totalReal() {
        lifecycleScope.launch(Dispatchers.IO) {
            var totalCount = 0

            totalCount += mList.sumOf {
                it as DepotInput
                it.quantity.intValue
            }

            withContext(Dispatchers.Main) {
                mBinding.depotReal.text = "$totalCount"
            }
        }
    }

}